package com.tfswx.jcyw.dmzc.component;

import com.intellij.util.ui.ListTableModel;
import com.tfswx.jcyw.dmzc.dto.ZcbzTableItem;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.text.View;
import java.awt.*;

/**
 * @author ricky
 * @date 2022/12/29
 */
public class ZcbzTableCellRenderer implements TableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable jTable, Object value, boolean isSelect, boolean hasFocus, int row, int col) {
        ListTableModel<ZcbzTableItem> model = (ListTableModel<ZcbzTableItem>) jTable.getModel();
        ZcbzTableItem item = model.getItem(row);

        JLabel jLabel = new JLabel();
        jLabel.setVerticalAlignment(SwingConstants.TOP);
        jLabel.setVerticalTextPosition(SwingConstants.BOTTOM);
        jLabel.setOpaque(true);
        jLabel.setText(getString(value, item.getSfktx()));

        if (!item.getSfktx()) {
            jLabel.setFont(new Font(null, Font.BOLD, 20));
        }
//        if (isSelect) {
//            jLabel.setForeground(jTable.getSelectionForeground());
//            jLabel.setBackground(jTable.getSelectionBackground());
//        }

        TableColumnModel columnModel = jTable.getColumnModel();

        int maxPreferredHeight = 0;
        for (int i = 0; i < jTable.getColumnCount(); i++) {
            String s = "<html>" + jTable.getValueAt(row, i) + "</html>";
            if (col == i) {
                s = jLabel.getText();
            }
            int width = columnModel.getColumn(i).getWidth();
            View v = BasicHTML.createHTMLView(jLabel, s);
            v.setSize(width, Integer.MAX_VALUE);
            maxPreferredHeight = Math.max(maxPreferredHeight, (int) v.getMinimumSpan(View.Y_AXIS));
        }

        jTable.setRowHeight(row, maxPreferredHeight + 10);
//        Dimension dimension = new Dimension(columnModel.getColumn(col).getWidth(), maxPreferredHeight + 20);
//        jLabel.setPreferredSize(dimension);
//        jLabel.setMinimumSize(dimension);
//        jLabel.setMaximumSize(dimension);
        return jLabel;
    }

    private String getString(Object value, boolean sfktx) {
        if (value == null) {
            return sfktx ? "" : "——";
        }
        if (StringUtils.isBlank(String.valueOf(value))) {
            return sfktx ? "" : "——";
        }
        return "<html>" + String.valueOf(value).trim() + "</html>";
    }
}
